package com.yonyou.crm.cum.customer.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yonyou.crm.base.doc.service.BaseDocDetailBizServiceImpl;
import com.yonyou.crm.common.biz.service.BaseBizServiceImpl;
import com.yonyou.crm.common.enumeration.service.EnumBizServiceImpl;
import com.yonyou.crm.common.field.handler.FieldRelationHandler;
import com.yonyou.crm.common.field.relation.EnumFieldRelation;
import com.yonyou.crm.common.field.relation.FieldRelation;
import com.yonyou.crm.common.field.relation.RefFieldRelation;
import com.yonyou.crm.common.login.context.LoginContextConstant;
import com.yonyou.crm.common.model.util.ModelUtil;
import com.yonyou.crm.common.page.entity.Page;
import com.yonyou.crm.cum.customer.dynamic.DymGCumAssignMyself;
import com.yonyou.crm.cum.customer.dynamic.DymGCumBackMyself;
import com.yonyou.crm.cum.customer.dynamic.DymGCumOrgAssign;
import com.yonyou.crm.cum.customer.dynamic.DymGCumOrgBack;
import com.yonyou.crm.cum.customer.entity.CustomerRelusersVO;
import com.yonyou.crm.cum.customer.entity.CustomerSalesDO;
import com.yonyou.crm.cum.customer.entity.CustomerSalesVO;
import com.yonyou.crm.cum.customer.entity.CustomerVO;
import com.yonyou.crm.sys.dynamic.impl.DynamicServiceImpl;
import com.yonyou.crm.sys.org.entity.SysOrgVO;
import com.yonyou.crm.sys.org.service.SysOrgBizServiceImpl;
import com.yonyou.crm.sys.user.entity.UserVO;
import com.yonyou.crm.sys.user.service.UserBizServiceImpl;
import com.yonyou.iuap.context.InvocationInfoProxy;

@Service
public class GroupCustomerSalesBizServiceImpl extends BaseBizServiceImpl<CustomerSalesDO>{

	@Autowired
	private SysOrgBizServiceImpl orgService;
	@Autowired
	private UserBizServiceImpl userService;
	@Autowired
	private BaseDocDetailBizServiceImpl baseDocDetailBizService;
	@Autowired
	private EnumBizServiceImpl enumService;
	@Autowired
	private DynamicServiceImpl dynamicService;
	@Autowired
	private CustomerSalesBizServiceImpl saleService;
	@Autowired
    private CustomerRelusersBizServiceImpl cusreluserService;
	@Autowired
    private CustomerBizServiceImpl customerService;
    @Autowired
    private GroupCustomerBizServiceImpl gCustomerService;
	
	public List<CustomerSalesVO> selectByCustomer(Map<String, Object> param) {
		List<CustomerSalesDO> doList = dao.selectVoList(CustomerSalesDO.class, "selectByCustomer", param);
		List<CustomerSalesVO> voList = ModelUtil.copyModelList(doList, CustomerSalesVO.class);
		transCustomerSale(voList);
		return voList;
	}
	
	public Page<CustomerSalesVO> getList(Page<CustomerSalesVO> page,Map<String, Object> paramMap){
		Page<CustomerSalesDO> doPage = super.pageSelect(CustomerSalesDO.class,page, paramMap.keySet().toArray(new String[0]), paramMap.values().toArray(new Object[0]));
		Page<CustomerSalesVO> voPage  = ModelUtil.copyPageModel(doPage, CustomerSalesVO.class);
		return voPage;
	}
	
	public CustomerSalesVO getDetail(Long id){
		CustomerSalesDO sDO = super.getVOById(CustomerSalesDO.class, id);
		CustomerSalesVO vo = ModelUtil.copyModel(sDO, CustomerSalesVO.class);
		return vo;
	}
	
	protected void beforeSaveVO(CustomerSalesDO sDO){
		super.beforeSaveVO(sDO);
		if (sDO.getCreatedTime() == null) {
			sDO.setCreatedTime(new Date());
		}
		if (sDO.getCreatedUserId() == null) {
			sDO.setCreatedUserId(Long.valueOf(InvocationInfoProxy.getParameter(LoginContextConstant.UserId)));
		}
	}
	
	public CustomerSalesVO insert(CustomerSalesVO vo){
		CustomerSalesDO sDO = super.saveVO(ModelUtil.copyModel(vo, CustomerSalesDO.class));
		vo = ModelUtil.copyModel(sDO, CustomerSalesVO.class);
		transCustomerSale(Arrays.asList(vo));
		return vo;
	}
	
	
	public CustomerSalesVO update(CustomerSalesVO vo) {
		CustomerSalesDO sDO = super.updateVO(ModelUtil.copyModel(vo, CustomerSalesDO.class));
		vo = ModelUtil.copyModel(sDO, CustomerSalesVO.class);
		transCustomerSale(Arrays.asList(vo));
		return vo;
	}
	
	
	public int delete(Long cumId){
		Map<String, Object> paraMap = new HashMap<String, Object>();
		
		String orgIdStr = (String)InvocationInfoProxy.getParameter("orgid");//所属公司
		String tenantIdStr = (String)InvocationInfoProxy.getTenantid();
		Long orgId = Long.parseLong(orgIdStr);
		Long tenantId = Long.parseLong(tenantIdStr);

		paraMap.put("orgId", orgId);
		paraMap.put("tenantId", tenantId);
		paraMap.put("cumId", cumId);
		return dao.deleteSql(CustomerSalesDO.class, "deleteByCumId", paraMap);
	}
	
	public int batchDeleteByCumIds(String[] cumIds){
		Map<String, Object> paraMap = new HashMap<String, Object>();
		
		String orgIdStr = (String)InvocationInfoProxy.getParameter("orgid");//所属公司
		String tenantIdStr = (String)InvocationInfoProxy.getTenantid();
		Long orgId = Long.parseLong(orgIdStr);
		Long tenantId = Long.parseLong(tenantIdStr);

		paraMap.put("orgId", orgId);
		paraMap.put("tenantId", tenantId);
		paraMap.put("cumIds", cumIds);
		return dao.deleteSql(CustomerSalesDO.class, "batchDeleteByCumIds", paraMap);
	}
	
	public List<CustomerSalesVO> transCustomerSale(List<CustomerSalesVO> customerSaleList) {
		
		List<FieldRelation<CustomerSalesVO>> relations = new ArrayList<FieldRelation<CustomerSalesVO>>();
		relations.add(new RefFieldRelation<CustomerSalesVO>(CustomerSalesVO.class, "orgId", new String[]{"orgName"}, orgService, "selectFieldsByIds"));
		relations.add(new RefFieldRelation<CustomerSalesVO>(CustomerSalesVO.class, "ownerDeptId", new String[]{"ownerDeptName"}, orgService, "selectFieldsByIds"));
		relations.add(new RefFieldRelation<CustomerSalesVO>(CustomerSalesVO.class, "ownerUserId", new String[]{"ownerUserName"}, userService, "selectFieldsByIds"));
		relations.add(new RefFieldRelation<CustomerSalesVO>(CustomerSalesVO.class, "level", new String[]{"levelName"}, baseDocDetailBizService, "selectFieldsByIds"));
		relations.add(new RefFieldRelation<CustomerSalesVO>(CustomerSalesVO.class, "state", new String[]{"stateName"}, baseDocDetailBizService, "selectFieldsByIds"));
		relations.add(new EnumFieldRelation<CustomerSalesVO>(CustomerSalesVO.class, "enableState", "enableStateName", enumService, "enable_state"));
		new FieldRelationHandler<CustomerSalesVO>().handler(customerSaleList, relations);
		
		return customerSaleList;
	}
	
	/**
	 * 集团客户批量分配
	 * @param orgIdStr
	 * @param cumIdStr
	 */
	public void batchAllocation(String orgIdStr, String cumIdStr) {
		UserVO user = getCurrentUser();
		String[] orgIds = orgIdStr.split(",");
		String[] cumIds = cumIdStr.split(",");
		Map<String, List<CustomerSalesVO>> result = getGroupSaleVOs(orgIds,
				cumIds);
		List<CustomerSalesVO> addVOs = result.get("add");
		List<CustomerSalesVO> updateVOs = result.get("update");
		for (CustomerSalesVO vo : addVOs) {
			//判断客户是否停用
			CustomerVO cumVo = gCustomerService.getDetail(vo.getCumId());
			if(cumVo.getEnableState() == 2){
				continue;
			}
			this.insert(vo);
			CustomerVO customer = gCustomerService.getDetail(vo.getCumId());
			Long[] relUserIdArr = handleRelUserList(vo.getCumId());
			SysOrgVO org = orgService.getDetail(vo.getOrgId());
			DymGCumOrgAssign gcumOrgAssign = new DymGCumOrgAssign(dynamicService, user, customer, org, relUserIdArr);
			gcumOrgAssign.execute();
			DymGCumAssignMyself gcumAssignMyself = new DymGCumAssignMyself(dynamicService, user, customer, org, relUserIdArr);
			gcumAssignMyself.execute();
		}
		for (CustomerSalesVO vo : updateVOs) {
			//判断客户是否停用
			CustomerVO cumVo = gCustomerService.getDetail(vo.getCumId());
			if(cumVo.getEnableState() == 2){
				continue;
			}
			this.update(vo);
			CustomerVO customer = gCustomerService.getDetail(vo.getCumId());
			Long[] relUserIdArr = handleRelUserList(vo.getCumId());
			SysOrgVO org = orgService.getDetail(vo.getOrgId());
			DymGCumOrgAssign gcumOrgAssign = new DymGCumOrgAssign(dynamicService, user, customer, org, relUserIdArr);
			gcumOrgAssign.execute();
			DymGCumAssignMyself gcumAssignMyself = new DymGCumAssignMyself(dynamicService, user, customer, org, relUserIdArr);
			gcumAssignMyself.execute();
		}
	}
	
	/**
	 * 处理集团客户批量分配
	 * @param orgIds
	 * @param cumIds
	 * @return
	 */
	private Map<String, List<CustomerSalesVO>> getGroupSaleVOs(String[] orgIds, String[] cumIds){
		Map<String, Object> param = new HashMap<>();
		param.put("cumIds",cumIds);
		param.put("orgIds", orgIds);
		List<CustomerSalesDO> doList = dao.selectVoList(CustomerSalesDO.class, "exsitSaleByOrg", param);
		List<CustomerSalesVO> sales = ModelUtil.copyModelList(doList, CustomerSalesVO.class);
		Map<String, CustomerSalesVO> saleInfos = new HashMap<String, CustomerSalesVO>();
		for(CustomerSalesVO sale:sales){
			saleInfos.put(sale.getOrgId().toString()+sale.getCumId(), sale);
		}
		Map<String, List<CustomerSalesVO>> result = new HashMap<String, List<CustomerSalesVO>>();
		List<CustomerSalesVO> addVOs = new ArrayList<CustomerSalesVO>();
		result.put("add", addVOs);
		List<CustomerSalesVO> updateVOs = new ArrayList<CustomerSalesVO>();
		result.put("update", updateVOs);
		String userIdStr = (String)InvocationInfoProxy.getParameter("id");// 用户id
		Long userId = Long.parseLong(userIdStr);
		String tenantIdStr = (String) InvocationInfoProxy.getTenantid();
        Long tenantId = Long.parseLong(tenantIdStr);
		Date date = new Date();
		for(String org:orgIds){
			for(String cum:cumIds){
				CustomerSalesVO salen = saleInfos.get(org+cum);
				if(null==salen){
					salen = new CustomerSalesVO();
					salen.setOrgId(new Long(org));
					salen.setCumId(new Long(cum));
					salen.setEnableState(1);
					salen.setEnableUserId(userId);
					salen.setEnableTime(date);
					addVOs.add(salen);
				}else {
					salen.setEnableState(1);
					salen.setEnableUserId(userId);
					salen.setEnableTime(date);
					salen.setTenantId(tenantId);
					updateVOs.add(salen);
				}
			}
		}
		return result;
	}

	/**
	 * 集团客户批量收回
	 * @param orgIdStr
	 * @param cumIdStr
	 */
	public void batchResume(String orgIdStr, String cumIdStr){
		UserVO user = getCurrentUser();
		String[] orgIds = orgIdStr.split(",");
		String[] cumIds = cumIdStr.split(",");
		Map<String, Object> param = new HashMap<>();
		param.put("cumIds",cumIds);
		param.put("orgIds", orgIds);
		List<CustomerSalesDO> doList = dao.selectVoList(CustomerSalesDO.class, "exsitSaleByOrg", param);
		List<CustomerSalesVO> sales = ModelUtil.copyModelList(doList, CustomerSalesVO.class);
		List<String> saleInfos = new ArrayList<String>();
		for(CustomerSalesVO sale:sales){
			//判断客户是否停用
			CustomerVO cumVo = gCustomerService.getDetail(sale.getCumId());
			if(cumVo.getEnableState() == 2){
				continue;
			}
			CustomerVO customer = gCustomerService.getDetail(sale.getCumId());
			Long[] relUserIdArr = handleRelUserList(sale.getCumId());
			SysOrgVO org = orgService.getDetail(sale.getOrgId());
			DymGCumOrgBack gcumOrgBack = new DymGCumOrgBack(dynamicService, user, customer, org, relUserIdArr);
			gcumOrgBack.execute();
			DymGCumBackMyself gcumOrgBackMyself = new DymGCumBackMyself(dynamicService, user, customer, org, relUserIdArr);
			gcumOrgBackMyself.execute();
			saleInfos.add(sale.getId().toString());
		}
		if(saleInfos.size()==0){
			return;
		}
		batchUpdateState(saleInfos.toArray(new String[0]), 2);
	}
	
	/**
	 * 批量更新销售信息状态
	 * @param ids
	 * @param enableState
	 */
	public void batchUpdateState(String[] ids, Integer enableState) {
		String userIdStr = (String)InvocationInfoProxy.getParameter("id");// 用户id
		Long userId = Long.parseLong(userIdStr);
		Date date = new Date();
		Map<String, Object> enableParaMap = new HashMap<String, Object>();
		enableParaMap.put("ids", ids);
		enableParaMap.put("enableState", enableState);
		enableParaMap.put("enableUserId", userId);
		enableParaMap.put("enableTime", date);
		enableParaMap.put("sysModifiedUserId", userId);
		enableParaMap.put("sysModifiedTime", date);
		dao.updateSql(CustomerSalesDO.class, "batchUpdateEnableState", enableParaMap);
	}
	
	/**
	 * 查询已分配的销售组织（状态为：启用）
	 * @param cumIdStr
	 * @return
	 */
	public List<CustomerSalesVO> getExistOrg(String cumIdStr) {
		String[] cumIds = cumIdStr.split(",");
		Map<String, Object> param = new HashMap<>();
		param.put("cumIds",cumIds);
		List<CustomerSalesDO> doList = dao.selectVoList(CustomerSalesDO.class, "existOrgByCumIds", param);
		List<CustomerSalesVO> result = ModelUtil.copyModelList(doList, CustomerSalesVO.class);
		transCustomerSale(result);
		return result;
	}
	
	private Long[] handleRelUserList(Long cumId){
		Long[] idArr = new Long[]{};
		List<Long> idList = new ArrayList<Long>();
		//查询公司客户负责人，添加到dynamic_follow表中
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("cumId", cumId);
		param.put("tenantId", InvocationInfoProxy.getTenantid());
		List<CustomerSalesVO> salesList = saleService.selectByCustomer(param);
		if(salesList != null && salesList.size() > 0){
			CustomerSalesVO cumSale = salesList.get(0);
			idList.add(cumSale.getOwnerUserId());
		}
		//查询客户参与人，添加到dynamic_follow表中
		List<CustomerRelusersVO> refuserList = cusreluserService.getCumRelusers(cumId);
		if(refuserList != null && refuserList.size() > 0){
			for(CustomerRelusersVO relUser : refuserList){
				idList.add(relUser.getUserId());
			}
			if(idList != null && idList.size() > 0){
				idArr = idList.toArray(new Long[0]);
			}
		}
		return idArr;
	}
	
	/**
	 * 获取当前登录用户
	 * @return
	 */
	private UserVO getCurrentUser(){
		Long curUser = Long.parseLong(InvocationInfoProxy.getParameter(LoginContextConstant.UserId));
		UserVO user = userService.getDetail(curUser);
		return user;
	}
}